package com.ruoyi.alipay.controller;

import com.ruoyi.alipay.domain.AlipayOrder;
import com.ruoyi.alipay.domain.PaymentSettlement;
import com.ruoyi.alipay.service.AlipayService;
import com.ruoyi.alipay.service.PaymentSettlementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pay/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentSettlementService paymentSettlementService;

    //创建订单
    @PostMapping("/create")
    public String createOrder(@RequestBody AlipayOrder order) {
        try {
            // 保存订单信息到数据库
            PaymentSettlement payment = new PaymentSettlement();
            payment.setOutTradeNo(order.getOutTradeNo());
            payment.setTotalAmount(order.getTotalAmount());
            payment.setProductName(order.getBody());
            payment.setTradeStatus("WAIT_BUYER_PAY");
            payment.setUserId(order.getUserId());
            payment.setGmtCreate(new Date());
            int result = paymentSettlementService.insert(payment);
            log.info("保存订单结果：{}, 订单号：{}", result, order.getOutTradeNo());

            return alipayService.createOrder(order);
        } catch (Exception e) {
            log.error("创建订单异常", e);
            throw e;
        }
    }

    //支付回调
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        try {
            //-----
            // 记录回调请求基本信息
            log.info("收到支付宝回调请求，URL: {}, Method: {}",
                    request.getRequestURL(),
                    request.getMethod());
            //-----
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            log.info("支付宝回调参数：{}", params);

            //-----
            // 将回调参数详细记录下来，使用debug级别防止信息量过大
            if(log.isDebugEnabled()) {
                log.debug("支付宝回调详细参数：{}", params);
            } else {
                log.info("支付宝回调参数概览 - out_trade_no: {}, trade_status: {}",
                        params.get("out_trade_no"),
                        params.get("trade_status"));
            }
            //-----
            // 验证签名
            if (alipayService.verifyNotify(params)) {
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                String tradeStatus = params.get("trade_status");
                String buyerId = params.get("buyer_id");
                String totalAmount = params.get("total_amount");

                log.info("订单支付成功：订单号：{}，支付宝交易号：{}, 交易状态：{}", outTradeNo, tradeNo, tradeStatus);
                log.info("待验证参数：{}", params);
//                log.info("使用的公钥：{}", alipayPublicKey);

                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    PaymentSettlement payment = new PaymentSettlement();
                    payment.setOutTradeNo(outTradeNo);
                    payment.setTradeNo(tradeNo);
                    payment.setTradeStatus(tradeStatus);
                    payment.setBuyerId(buyerId);
                    payment.setTotalAmount(new BigDecimal(totalAmount));
                    payment.setGmtPayment(new Date());
                    payment.setGmtModified(new Date());

                    int result = paymentSettlementService.updateByOutTradeNo(payment);
                    log.info("更新订单状态结果：{}", result);

                    // 必须返回 success，否则支付宝会重复通知
                    return "success";
                }
            }
            return "failure";
        } catch (Exception e) {
            log.error("处理支付宝回调异常", e);
            return "failure";
        }
    }
}